import dgram from 'dgram'
import Emitter from '@multi-kit/emitter'


// const list = [
//   {
//     port: 10115,
//     host: '192.168'
//   }
// ]


// function createUDPLinks() {

// }


export default class UDPServer extends Emitter {
  constructor(localPort = 0) {
    super()
    this.localPort = localPort
    this.socket = dgram.createSocket('udp4')

    this.socket.on('error', (err) => {
      console.error(`UDP 错误: ${err.message}`)
      this.socket.close()
    })

    this.socket.on('message', (msg, rinfo) => {
      console.log('message----------->', msg)
      this._events['message']?.forEach((event) => {
        event(msg, rinfo)
      })
    })

    this.socket.bind(this.localPort, () => {
      console.log(`UDPServer listening on ${this.localPort}`)
    })
  }

  /**
   * 发送数据包
   * @param {Buffer|string} data - 要发送的数据
   */
  send(port, host,  data) {
    if (typeof data === 'string') {
      data = Buffer.from(data)
    }
    this.socket.send(data, port, host, (err) => {
      if (err) {
        console.error('UDP 发送错误:', err.message)
      }
    })
  }

  sendAsync(port, host, data, { parser, acceptChecker }) {
    let hasAccept = false
    return new Promise((resolve, reject) => {
      if (typeof data === 'string') {
        data = Buffer.from(data)
      }

      const onMessage = (msg, rinfo) => {
        const message = parser(msg, rinfo)

        if (acceptChecker(message)) {
          console.log('msg', msg)
          hasAccept = true
          this.off('message', onMessage)
          resolve(message)
        }
      }
      this.on('message', onMessage)
      const timer = setTimeout(() => {
        if (!hasAccept) {
          this.off('message', onMessage)
          reject(new Error('Timeout waiting for response'))
        }
        clearTimeout(timer)
      }, 1000 * 10)

      console.log("send++++++++++>", data)
      this.socket.send(data, port, host)
    })
  }

  close() {
    this.socket.close(() => {
      console.log('UDP 已关闭')
    })
  }
}
